/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on May 23, 2011, 9:10:45 AM
 */

package ui;



import interfaces.base.UIBean;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.lang.reflect.Method;
import java.util.ArrayList;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.JTextComponent;
import imp.base.*;
import interfaces.base.ValidateInt;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.lang.String;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
/**
 *
 * @author eisa
 */

public class MainFrame extends javax.swing.JFrame implements UIBean{

    /** Creates new form MainFrame */

    private Object backBean;
    private ArrayList<JTextComponent> bindingText;
    private ArrayList<JButton> bindingbutton;
    private ArrayList<JToggleButton> bindingToggle;
    private ArrayList<JMenuItem> bindingmenu;
    private ArrayList<JLabel> bindingError;
    private ValidateInt validateInt; 
    
    
    public MainFrame() {
        lookAndFeelDesign();
        bindingText=new ArrayList<JTextComponent>();
        bindingbutton=new ArrayList<JButton>();
        bindingToggle=new ArrayList<JToggleButton>();
        bindingmenu=new ArrayList<JMenuItem>();
        bindingError=new ArrayList<JLabel>();
        
        initComponents();   
    }
    
    /**
     * used to create arrays of JButton , JTextComponent 
     * JToggleButton , JLabel that used to show errors
     * 
     * @param con Container that loop in component inside it 
     */
    protected  final void initial(Container con)
    {
        for(Component com: con.getComponents())
        {
           if(com.getName() != null)
           {
           if(com instanceof JTextComponent)
           {
           JTextComponent jTextComponent=(JTextComponent)com;    
           bindingText.add(jTextComponent);
           textInitial(jTextComponent);
           }
           else if (com instanceof JButton)
           {
           bindingbutton.add((JButton)com);
           buttonInitial((JButton)com);
           }
           else if (com instanceof JToggleButton)
           {
           bindingToggle.add((JToggleButton)com);
           }
           else if (com instanceof JLabel)
           {
           bindingError.add((JLabel)com);
           }
           }
        }

    }
    
    /**
     * This method used to set text object by 
     * add listener to text when key released 
     * go to set data 
     * @param jTextComponent 
     */
    private void textInitial(final JTextComponent jTextComponent)
    {
   jTextComponent.addKeyListener(new KeyAdapter() {
   public void keyReleased(KeyEvent e)
   {
      setValue(jTextComponent.getName(), jTextComponent.getText());
   }
   });
   }
    
    /**
     * This method used to create array of JMeunlist 
     * @param jMenuBar 
     */
    
    protected  final void initialMenu(JMenuBar jMenuBar)
    {
       for(int i=0;i<jMenuBar.getMenuCount();i++)
       {
           for(int j=0;j<jMenuBar.getMenu(i).getItemCount();j++)
           {
               final JMenuItem jMenuItem=jMenuBar.getMenu(i).getItem(j);
               bindingmenu.add(jMenuItem);
                jMenuItem.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                       callMethod(jMenuItem.getName()); 
                    }
                });
                
           }
       }
    }
    
    /**
     * This method used to handle button clicked 
     * by calling method in backing beans
     * @param button 
     */
    private void buttonInitial(final JButton button)
    {
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                callMethod(button.getName());
            }
        });
    }

    /**
     * This method used to invoked method in 
     * backing beans by take method name
     * @param methodName 
     */
    
    private void callMethod(String methodName)
    {
       try{
       Method method= backBean.getClass().getDeclaredMethod(methodName,null);
       method.invoke(backBean, null);
       }
       catch(Exception ex)
       {
       ex.printStackTrace();
       }
    }

    
    /**
     * used to call methods set by naming convention
     * @param name
     * @param value 
     */
    
    private void setValue(String name,String value)
    {
      try{
       String methodName=getNamingConv(name,Type.set.val);
       Method method= backBean.getClass().getMethod(methodName, String.class);
       method.invoke(backBean, value);
       }
       catch(Exception ex)
       {
       ex.printStackTrace();
       }
    }
    
    
    
    private Object getValue(String name)
    {
       Object resObject=null;
       try{
       String methodName=getNamingConv(name,Type.get.val);
       Method method= backBean.getClass().getMethod(methodName, null);
       resObject=method.invoke(backBean, null);
       }
       catch(Exception ex)
       {
       ex.printStackTrace();
       }
       finally
       {
       return resObject;
       }
    }
    
    
    private String getNamingConv(String value,String type)
    {
       char[] val=value.toCharArray();
       char[] val2={val[0]};
       String first=new String(val2);
       first=first.toUpperCase();
       val[0]=first.charAt(0);
       first=new String(val);
       value=type+first;
       return value;
    }
    
    private void lookAndFeelDesign()
    {
    try {
    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            UIManager.setLookAndFeel(info.getClassName());
            break;
        }
       }
      } catch (UnsupportedLookAndFeelException e) {
    // handle exception
    } catch (ClassNotFoundException e) {
    // handle exception
} catch (InstantiationException e) {
    // handle exception
} catch (IllegalAccessException e) {
    // handle exception
}
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    public void update(String name, String value) {
       
    }
    
    public void update() {
        textBind();
    }
    
    private void textBind()
    {
    for(final JTextComponent textComponent:bindingText)
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              Object objectval=getValue(textComponent.getName());
              String val=  objectval==null?"":objectval.toString();
              textComponent.setText(val);
            }
        });
    }
    
    public void register(Object backBean) {
        this.backBean=backBean;
        this.validateInt=(ValidateInt) backBean;
        update();
    }
    
    public boolean closeUi() {
        this.setVisible(false);
        this.dispose();
        return true;
    }
    
    
    
    
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    public void showError(ValidationClass validationClass) {
        for(JLabel jLabel:bindingError)
           if(jLabel.getName().equalsIgnoreCase(validationClass.getComponentError()))
               jLabel.setText(validationClass.getErrorMsg());
    }
}
